package com.miage.itrading.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;

import com.miage.itrading.dao.CotationDAO;
import com.miage.itrading.entites.Cotation;
import com.miage.itrading.metier.CoursTempsReelDaemon;
import com.miage.itrading.utils.Const;
import com.miage.itrading.utils.Util;

public class PartieGauche extends JInternalFrame {
	
	public static float X 		= 0;
	public static float Y		= 0;
	public static float WIDTH 	= 0.15f;
	public static float HEIGHT 	= 0.5f;
	
	private Object[][] rows;
	
	
	private static CotationDAO c = new CotationDAO();
	
	private static FenetrePrincipale parent;	
	
	private Cotation cotation; 

	private static final long serialVersionUID = 3319394193523337002L;
	
	private static ArrayList<Integer> listeLignesAvecListener;
	
	
	public PartieGauche(FenetrePrincipale parent){
        super("Cotation - iTrading", true, true, true, true);
		
		PartieGauche.parent = parent;

		
		setLocation((int) (parent.getScreenSize().width * X), 
					(int) (parent.getScreenSize().height * Y));
		
		setSize((int) (parent.getScreenSize().width * WIDTH), 
				(int) (parent.getScreenSize().height * HEIGHT));
		setResizable(true);
		
		listeLignesAvecListener = new ArrayList<Integer>();
	}
	
    private class MyTableModel extends AbstractTableModel {
		private static final long	serialVersionUID	= 1L;
		
		private String[] columnNames	= {"Nom.", "Val.", "Var."};
        private Object[][] data			= rows;

        
        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
        	if (col == 0) {
        		return data[row][col];
        	}
        	else if (col == 1) {
        		return Float.valueOf(((String) data[row][col]).replace("€", ""));
        	}
        	else {
        		return Float.valueOf(((String) (data[row][col])).replace("%", ""));	
        	}
            
        }

        public boolean isCellEditable(int row, int col) {
        	return false;
        }

        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
        }
    }
    
    private class CellRenderer extends DefaultTableCellRenderer {
		private static final long	serialVersionUID	= 1L;

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			
			/**
			 * On effectue le traitement sur toute la ligne d'un seul coup,
			 * pas besoin de le faire 3 fois
			 */
			if (column == 0) {
				if (row > 0) {
					Component cell1 = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, 0);
					Component cell2 = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, 1);
					Component cell3 = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, 2);

					/**
					 * Affiche la valeur sélectionnée si elle ne l'est pas déjà
					 */
					if (isSelected) {
						try {
							Cotation cotationToBeDisplayed = c.getCotationByName(String.valueOf(table.getValueAt(row, 0)));
							
							if (!parent.getCotationAffichee().equals(cotationToBeDisplayed)) {
								parent.afficheCours(cotationToBeDisplayed);
							}
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
					
					/**
					 * Ajoute le thread temps réel à la valeur s'il n'a pas encore été ajouté
					 */
					if (listeLignesAvecListener.contains(row) == false) {
						System.out.println("Thread pour ligne " + row);
						listeLignesAvecListener.add(row);
						
						try {
							CotationDAO c = new CotationDAO();
							CoursTempsReelDaemon tr = new CoursTempsReelDaemon(c.getCotationByName(String.valueOf(table.getValueAt(row, 0))),
																			   table, row, 1, 2);
							tr.start();
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
					
					String cellValue = String.valueOf(table.getValueAt(row, 2));
					
					if (cellValue.substring(0, 1).contentEquals("+")) {
						cell1.setForeground(Const.VARIATION_POSITIVE);
						cell1.setForeground(Const.VARIATION_POSITIVE);
						cell1.setForeground(Const.VARIATION_POSITIVE);
					}
					else {
						cell1.setForeground(Const.VARIATION_NEGATIVE);
						cell2.setForeground(Const.VARIATION_NEGATIVE);
						cell3.setForeground(Const.VARIATION_NEGATIVE);
					}
				}
			}
			
			return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
		}
	}
    
	private class VariationComparator implements Comparator<Float> {

		public int compare(Float a, Float b) {
			return a.compareTo(b);
		}
	}
    
    
	
	public void build() {
		if (cotation != null) {
			try {
				CotationDAO cotationDAO = new CotationDAO();
				ArrayList<Integer> composition = (ArrayList<Integer>) (cotationDAO.getIndiceComposition(cotation.getIdCotation()));
				
				if (composition.size() > 0) {
					
					rows = new Object[composition.size()][3];
					
					Cotation c;
					for (int i=0 ; i<composition.size() ; ++i) {
						c = cotationDAO.getCotationById(composition.get(i));
						
						rows[i][0] = c.getNom();
						rows[i][1] = String.valueOf(c.getLastValeur() + " €");
						rows[i][2] = Util.variationCoursString(c);
					}
					
					JPanel panel = new JPanel();
					
					String[] columnNames	= {"Nom.", "Val.", "Var."};
					DefaultTableModel model = new DefaultTableModel(rows, columnNames);
					
					JTable table = new JTable(model);
					MyTableModel modeleDynamique =  new MyTableModel();
					
					table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			        table.setAutoCreateRowSorter(true);
			        table.setModel(modeleDynamique);
			         
			        TableRowSorter<MyTableModel> sorter = new TableRowSorter<MyTableModel>(modeleDynamique);	 
					sorter.setComparator(1, new VariationComparator());
					sorter.setComparator(2, new VariationComparator());
					table.setRowSorter(sorter);
			        
					JTableHeader header = table.getTableHeader();
			        header.setTable(table);
			        header.setCursor(new Cursor(Cursor.HAND_CURSOR));
			        header.setBackground(new Color(200, 200, 200));
					
			        table.setDefaultRenderer(Object.class, new CellRenderer());
			        
			        JScrollPane pane = new JScrollPane(table);
			        
			        pane.setPreferredSize(this.getSize());
			        
			        panel.setSize(this.getSize());
			        Dimension d = this.getSize();
			        d.setSize(d.getWidth() - 10 , d.getHeight() - 10);
			        pane.setSize(d);
			        table.setSize(this.getSize());
					
					panel.add(pane, BorderLayout.WEST);
					add(panel, BorderLayout.WEST);
					  
					repaint();
					updateUI();			        
				}
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
			updateUI();
			repaint();
		}
		else {
			System.out.println("Cotation null");
		}
	}
	
	public Cotation getCotation() {
		return cotation;
	}

	public void setCotation(Cotation cotation) {
		this.cotation = cotation;
	}
}
